package org.easymodelers.gmf.update;

import java.io.File;
import java.util.List;
import java.util.Map.Entry;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
import java.util.jar.Attributes.Name;

import org.easymodelers.gmf.GmfDiagramPluginUpdate;
import org.easymodelers.gmf.utils.PluginUtils;

public class AddPluginDependencyUpdate extends AbstractManifestUpdate implements GmfDiagramPluginUpdate {
	private List<String> plugins;

	public AddPluginDependencyUpdate() {
	}

	public AddPluginDependencyUpdate(List<String> plugins) {
		this.plugins = plugins;
	}

	private String getWorkspaceDirectory() {
		File file = new File(".");
		String absolutePath = file.getAbsolutePath();
		absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
		absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
		return absolutePath;
	}
	
	public void updateDiagramPlugin(String plugin) {
		StringBuffer manifestPath = new StringBuffer();
		manifestPath.append(getWorkspaceDirectory());
		manifestPath.append(File.separator);
		manifestPath.append(plugin);
		manifestPath.append(File.separator);
		manifestPath.append("META-INF");
		manifestPath.append(File.separator);
		manifestPath.append("MANIFEST.MF");
		
		Manifest manifest = PluginUtils.loadManifest(manifestPath.toString());
		Attributes attributes = manifest.getMainAttributes();//"Require-Bundle");
		for (Entry<Object, Object> entry : attributes.entrySet()) {
			Name key = (Name) entry.getKey();
			if ("Require-Bundle".equals(key.toString())) {
				String value = (String) entry.getValue();
				StringBuffer newValue = new StringBuffer();
				newValue.append(value);
				for (String pluginToAdd : plugins) {
					if (value.indexOf(pluginToAdd)==-1) {
						newValue.append(",");
						newValue.append(pluginToAdd);
					}
				}
				entry.setValue(newValue.toString());
			}
		}
		
		PluginUtils.storeManifest(manifestPath.toString(), manifest);
	}

	public List<String> getPlugins() {
		return plugins;
	}

	public void setPlugins(List<String> plugins) {
		this.plugins = plugins;
	}

}
